package com.gisuni.sddc.platformManager.service;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import com.gisuni.sddc.platformManager.dao.RoleDao;
import com.gisuni.sddc.platformManager.model.PageInfo;
import com.gisuni.sddc.platformManager.model.Response;
import com.gisuni.sddc.platformManager.model.RoleInfo;
import com.gisuni.sddc.platformManager.model.RoleRModule;
import com.gisuni.sddc.platformManager.model.RoleRResource;
import com.gisuni.sddc.platformManager.model.Tree;
import com.gisuni.sddc.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

@IocBean
public class RoleService   {

	private Log log = Logs.getLog(RoleService.class);    
    @Inject
    private RoleDao roleDao;
  
    public void findDataGrid(PageInfo pageInfo) {
//        pageInfo.setRows(roleMapper.findRolePageCondition(pageInfo));
//        pageInfo.setTotal(roleMapper.findRolePageCount(pageInfo));
    }

  
    public List<Tree> findTree() {
        List<Tree> trees = new ArrayList<Tree>();
        String sql = "select t.ROLE_ID,t.ROLE_PARENT_ID,t.ROLE_NAME,t.ROLE_TYPE,t.DESCRIPTION from SDDCGISPLATFORM.ROLE_INFO t";
        List<RoleInfo> roles = roleDao.findRole(sql);
        Tree root = new Tree();
        root.setId("0");
        root.setText("所有角色");
        trees.add(root);
        for (RoleInfo role : roles) {
            Tree tree = new Tree();
            tree.setId(role.getRoleId());
            tree.setText(role.getRoleName());
            tree.setPid("0");
            trees.add(tree);
        }
        return trees;
    }

  
    public void addRole(RoleInfo role) {
//        int insert = roleMapper.insert(role);
//        if (insert != 1) {
//            LOGGER.warn("插入失败，参数：{}", role.toString());
//            throw new ServiceException("插入失败");
//        }
    }

  
    public Response deleteRoleById(String id) {
   	 Response res = new Response();
   	 res.setSuccess(false);
   	 try{
     	RoleInfo role = new RoleInfo();
     	role.setRoleId(id);
    	boolean flag  = roleDao.delRole(role);
    	 if(flag){
    		 res.setSuccess(true);
    	 }
    	 return res;
   	 }catch(Exception e){
   		 e.printStackTrace();
   		 log.error(e);
   		 res.setMsg("操作失败");
   		 return res;
   	 }
    }

  
    public RoleInfo findRoleById(String id) {
      return roleDao.findRoleById(id);
    }

  
    public Response updateRole(HttpServletRequest request) {
      	 Response res = new Response();
       	 res.setSuccess(false);
       	 String roleName = request.getParameter("name");
    		 String description = request.getParameter("description");
    		 String id = request.getParameter("id");
    		 String type = request.getParameter("type");
    		 String[] roleArea = request.getParameterValues("roleArea");
    		 String roleAreaType = request.getParameter("roleAreaType");//可是区域类型
    		 //TODO 类型需与上级部门有限制 ??s
    		 RoleInfo role = new RoleInfo();
    		 role.setRoleName(roleName);
    		 role.setRoleType(type);
    		 role.setDescription(description);
    		 role.setRoleId(id);
    		 if(!StringUtil.isNullOrEmpty(roleAreaType)){
    			 role.setRoleAreaType(roleAreaType);
    		 }
    		 
    		 if(roleArea!=null && roleArea.length>0){
    			 String cat = "";
    			 for(String ro : roleArea){
    				 cat+=(ro+",");			 
    		     }
    			 role.setRoleArea(cat.substring(0,cat.length()-1));//可视区域
    		 }
    		 
    		 boolean flag  = roleDao.updateRole(role);
    		 if(flag){
    			 res.setSuccess(true);
    		 } 
    		 
    		return res;
    }

  
 
 


	public Response addRole(HttpServletRequest request) {
   	 Response res = new Response();
   	 res.setSuccess(false);
   	 String roleName = request.getParameter("name");
		 String description = request.getParameter("description");
//		 String parentId = request.getParameter("pid");
		 String type = request.getParameter("type");
		 String roleAreaType = request.getParameter("roleAreaType");//可是区域类型
		 String[] roleArea = request.getParameterValues("roleArea");
		 //TODO 类型需与上级部门有限制
		 
		 RoleInfo role = new RoleInfo();
		 role.setRoleName(roleName);
		 role.setRoleType(type);
		 role.setDescription(description);
		 role.setRoleAreaType(roleAreaType); //可视区域类型
		 role.setRoleId(UUID.randomUUID().toString().replaceAll("-", ""));
		 if(roleArea!=null && roleArea.length>0){
			 String cat = "";
			 for(String ro : roleArea){
				 cat+=(ro+",");			 
		     }
			 role.setRoleArea(cat.substring(0,cat.length()-1));//可视区域
		 }
		 boolean flag  = roleDao.addRole(role);
		 if(flag){
			 res.setSuccess(true);
		 } 
		 
		return res;
	}


 

	public Response queryBaseRoleAll(int from, int to, String roleName) {
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
 
		try {
 
			String result = roleDao.queryBaseRoleAll(  from,  to,  roleName);
			int total = roleDao.queryBaseRoleCount( roleName);
			response.setSuccess(true);
			response.setResult(result);
			response.setTotal(total);
			return response;
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			response.setMsg("查询失败");
			return response;
		}
		
	}


	public String getPrivilegeByRoleId(String id) {
		StringBuffer resultSbf = new StringBuffer();
		if(!StringUtil.isNullOrEmpty(id)){
			//加了c就必然有一条数据 
			String findModuleIdSql = "select 'c,'||wm_concat(t.module_id) ids from role_r_module t where role_id = '"+id+"'";
			String findResourceIdSql = "select 'c,'||wm_concat(t.resource_id) ids from role_r_resource t where role_id = '"+id+"'";
			
			String moduleResult = roleDao.querySql(findModuleIdSql);
			String m = jsonToString(moduleResult,"IDS");
			if(!StringUtil.isNullOrEmpty(m)){
				resultSbf.append(m);
			}
			
			String resourceResult = roleDao.querySql(findResourceIdSql);
			resultSbf.append("|");
			m = jsonToString(resourceResult,"IDS");
			if(!StringUtil.isNullOrEmpty(m)){
				resultSbf.append(m);
			}
		}
		
		return resultSbf.toString();
	}
	
	public String jsonToString(String json ,String name){
		
		JSONArray resultJsonArr = new JSONArray(json);
		StringBuffer sbf = new StringBuffer();
		if (resultJsonArr != null && resultJsonArr.length() > 0) {
			for (int i = 0; i < resultJsonArr.length(); i++) {
				JSONObject ret = (JSONObject) resultJsonArr.get(i);
				Iterator iterator = ret.keys();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					 
					if(name.equals(key)){
						String value = (String) ret.get(key);
						sbf.append(value);
					}
				}	
			}
		}
//		System.out.println(sbf.toString());
		return sbf.toString();
		
	}


	public Response grantModule(String id, String moduleIds) throws Exception{
		Response response = new Response();
		response.setSuccess(false);
		 boolean flag = false;
		 if(!StringUtil.isNullOrEmpty(id)){
			 //清除
			 String sql = "delete from SDDCGISPLATFORM.ROLE_R_MODULE where role_id = '"+id+"'";
			 
			  flag = roleDao.executeSQL(sql);
			  if(flag){
					 //新增
					 String[] moduleIdArr = moduleIds.split(",");
					 String insert = null;
					
					 if(moduleIdArr.length>0){
						 for(String moduleId : moduleIdArr){
								
							 if(!StringUtil.isNullOrEmpty(moduleId)){
								 RoleRModule entity = new RoleRModule();
								 entity.setId(UUID.randomUUID().toString().replaceAll("-", ""));;
								 entity.setModuleId(moduleId);
								 entity.setCreateTime(new Date());
								 entity.setRoleId(id);
								 flag = roleDao.addRoleRModule(entity);
							 }
						 }
					 }
					 flag = true;
			  }
			 if(flag){
				 response.setSuccess(true);
			 }
			 
			 
		 }
		return response;
	}


	public Response grantResource(String roleId, String resourceIds) {
		Response response = new Response();
		response.setSuccess(false);
		 boolean flag = false;
		 if(!StringUtil.isNullOrEmpty(roleId)){
			 //清除
			 String sql = "delete from SDDCGISPLATFORM.ROLE_R_RESOURCE where role_id = '"+roleId+"'";
			 
			  flag = roleDao.executeSQL(sql);
			  if(flag){
					 //新增
					 String[] resourceIdArr = resourceIds.split(",");
					 String insert = null;
					
					 if(resourceIdArr.length>0){
						 for(String moduleId : resourceIdArr){
								
							 if(!StringUtil.isNullOrEmpty(moduleId)){
								 RoleRResource entity = new RoleRResource();
								 entity.setId(UUID.randomUUID().toString().replaceAll("-", ""));;
								 entity.setResourceId(moduleId);
								 entity.setCreateTime(new Date());
								 entity.setRoleId(roleId);
								 flag = roleDao.addRoleRResource(entity);
							 }
						 }
					 }
					 
					 flag = true;
			  }
			 if(flag){
				 response.setSuccess(true);
			 }
			 
			 
		 }
		return response;
	}

}
